package com.reeygu.item.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reeygu.item.mapper.GoodsMapper;
import com.reeygu.item.pojo.Goods;
import com.reeygu.item.service.GoodsService;
import com.reeygu.item.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
* @author a1304
* @description 针对表【t_goods】的数据库操作Service实现
* @createDate 2023-08-05 00:20:52
*/
@Slf4j
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods>
implements GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public List<GoodsVo> findAllGoodsVo() {
        return goodsMapper.findAllGoodsVo();
    }

    @Override
    public GoodsVo findGoodsVoByGoodsId(Long goodsId) {
        return goodsMapper.findAllGoodsVoByGoodsId(goodsId);
    }

    /**
     * 为了防止高并发出现超卖现象，在此处业务层也要重新查询一次库存数量
     * @param goodsId
     * @return
     */
    @Override
    public int deductGoods(Long goodsId) {
//        Goods goods = goodsMapper.selectById(goodsId);
//        goods.setGoodsStock(goods.getGoodsStock() - 1);
//        log.info("成功修改当前商品库存{} - 1 = {}", goods.getGoodsStock(), goods.getGoodsStock() - 1);
        //return goodsMapper.updateById(goods);
        // 上面的方式不安全，因为查询和修改是分开的，遇到高并发容易数据覆盖，优化成下面
        return this.update(new UpdateWrapper<Goods>().setSql("stock_count = stock_count - 1")
                .eq("goods_id", goodsId)
                .gt("stock_count", 0)) ? 1 : -1;
    }
}
